<template>
  <div class="repair-statistics" v-loading="loading">
    <!-- 维修汇总卡片 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="8" :md="8">
        <el-card shadow="hover" class="summary-card">
          <div class="summary-header">维修率</div>
          <div class="summary-value">{{ (chartData.repairRate.summary?.repairRate || 0).toFixed(2) }}%</div>
          <div class="summary-footer">
            <el-tooltip content="维修率 = 需维修数 / 总检验数" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            <span>总计需维修: {{ chartData.repairRate.summary?.repairCount || 0 }}件</span>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="8">
        <el-card shadow="hover" class="summary-card">
          <div class="summary-header">维修成本</div>
          <div class="summary-value">¥{{ formatNumber(chartData.repairCost.summary?.totalCost || 0) }}</div>
          <div class="summary-footer">
            <el-tooltip content="包括材料成本、人工成本和设备折旧" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            <span>平均成本: ¥{{ (chartData.repairCost.summary?.avgCost || 0).toFixed(2) }}/件</span>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="8">
        <el-card shadow="hover" class="summary-card">
          <div class="summary-header">维修合格率</div>
          <div class="summary-value">{{ (chartData.repairEvaluation.summary?.qualificationRate || 0).toFixed(2) }}%</div>
          <div class="summary-footer">
            <el-tooltip content="维修合格率 = 维修合格数 / 总维修数" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            <span>总计维修: {{ chartData.repairEvaluation.summary?.totalCount || 0 }}件</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
  
    
    <!-- 维修成本分析 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :sm="24" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>产品维修率比较</span>
          </div>
          <div class="chart-container" ref="productRepairChart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>按缺陷类型维修成本</span>
          </div>
          <div class="chart-container" ref="defectCostChart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :sm="24" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>月度维修成本趋势</span>
          </div>
          <div class="chart-container" ref="monthlyCostChart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>维修合格率趋势</span>
          </div>
          <div class="chart-container" ref="qualificationTrendChart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: "RepairStatistics",
  props: {
    queryParams: {
      type: Object,
      required: true
    },
    chartData: {
      type: Object,
      required: true
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      productRepairChart: null,
      defectCostChart: null,
      monthlyCostChart: null,
      qualificationTrendChart: null
    }
  },
  watch: {
    'chartData': {
      handler() {
        this.$nextTick(() => {
          this.initCharts();
        });
      },
      deep: true
    },
    'loading': {
      handler(newVal) {
        if (!newVal) {
          this.$nextTick(() => {
            this.initCharts();
          });
        }
      }
    }
  },
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    this.disposeCharts();
  },
  methods: {
    // 格式化数字，添加千位分隔符
    formatNumber(num) {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    
    initCharts() {
      this.initProductRepairChart();
      this.initDefectCostChart();
      this.initMonthlyCostChart();
      this.initQualificationTrendChart();
    },
    
    resizeCharts() {
      this.productRepairChart?.resize();
      this.defectCostChart?.resize();
      this.monthlyCostChart?.resize();
      this.qualificationTrendChart?.resize();
    },
    
    disposeCharts() {
      this.productRepairChart?.dispose();
      this.defectCostChart?.dispose();
      this.monthlyCostChart?.dispose();
      this.qualificationTrendChart?.dispose();
    },
    
    initProductRepairChart() {
      if (!this.$refs.productRepairChart) return;
      
      if (this.productRepairChart) {
        this.productRepairChart.dispose();
      }
      
      this.productRepairChart = echarts.init(this.$refs.productRepairChart);
      
      const productRepairRates = this.chartData.repairRate?.productRepairRates || [];
      if (productRepairRates.length === 0) return;
      
      // 按维修率降序排序
      const sortedData = [...productRepairRates].sort((a, b) => b.repairRate - a.repairRate);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const data = params[0].data;
            return `${params[0].name}<br/>
                   维修率: ${data.repairRate}%<br/>
                   维修数: ${data.repairCount}<br/>
                   总数: ${data.totalCount}`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}%'
          }
        },
        yAxis: {
          type: 'category',
          data: sortedData.map(item => item.productName),
          axisLabel: {
            interval: 0
          }
        },
        series: [
          {
            name: '维修率',
            type: 'bar',
            data: sortedData.map(item => ({
              value: item.repairRate,
              repairRate: item.repairRate,
              repairCount: item.repairCount,
              totalCount: item.totalCount
            })),
            itemStyle: {
              color: params => {
                const value = params.value;
                if (value <= 2) return '#67c23a';
                else if (value <= 5) return '#e6a23c';
                else return '#f56c6c';
              }
            },
            label: {
              show: true,
              position: 'right',
              formatter: '{c}%'
            }
          }
        ]
      };
      
      this.productRepairChart.setOption(option);
    },
    
    initDefectCostChart() {
      if (!this.$refs.defectCostChart) return;
      
      if (this.defectCostChart) {
        this.defectCostChart.dispose();
      }
      
      this.defectCostChart = echarts.init(this.$refs.defectCostChart);
      
      const defectTypeCosts = this.chartData.repairCost?.defectTypeCosts || [];
      if (defectTypeCosts.length === 0) return;
      
      // 按成本降序排序
      const sortedData = [...defectTypeCosts].sort((a, b) => b.totalCost - a.totalCost);
      
      const pieData = sortedData.map(item => ({
        name: item.defectTypeName || '未知缺陷',
        value: item.totalCost || 0
      })).filter(item => item.name && item.value > 0);
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: ¥{c} ({d}%)'
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 20,
          data: pieData.map(item => item.name).filter(name => name)
        },
        series: [
          {
            name: '维修成本',
            type: 'pie',
            radius: '55%',
            center: ['40%', '50%'],
            data: pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              formatter: '{b}: ¥{c}',
              show: pieData.length < 8
            }
          }
        ]
      };
      
      this.defectCostChart.setOption(option);
    },
    
    initMonthlyCostChart() {
      if (!this.$refs.monthlyCostChart) return;
      
      if (this.monthlyCostChart) {
        this.monthlyCostChart.dispose();
      }
      
      this.monthlyCostChart = echarts.init(this.$refs.monthlyCostChart);
      
      const monthlyCosts = this.chartData.repairCost?.monthlyCosts || [];
      if (monthlyCosts.length === 0) return;
      
      const xData = monthlyCosts.map(item => item.timePoint || item.month);
      const totalCostData = monthlyCosts.map(item => item.totalCost);
      const repairCountData = monthlyCosts.map(item => item.repairCount);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          formatter: function(params) {
            const month = params[0].name;
            const totalCost = params[0].value;
            const repairCount = params[1].value;
            const avgCost = repairCount > 0 ? (totalCost / repairCount).toFixed(2) : 0;
            
            return `${month}<br/>
                   总成本: ¥${totalCost}<br/>
                   维修数: ${repairCount}<br/>
                   平均成本: ¥${avgCost}/件`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: xData,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '维修成本',
            axisLabel: {
              formatter: '¥{value}'
            }
          },
          {
            type: 'value',
            name: '维修数量',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '维修成本',
            type: 'bar',
            data: totalCostData,
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '维修数量',
            type: 'line',
            yAxisIndex: 1,
            data: repairCountData,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#E6A23C'
            },
            lineStyle: {
              width: 2
            }
          }
        ]
      };
      
      this.monthlyCostChart.setOption(option);
    },
    
    initQualificationTrendChart() {
      if (!this.$refs.qualificationTrendChart) return;
      
      if (this.qualificationTrendChart) {
        this.qualificationTrendChart.dispose();
      }
      
      this.qualificationTrendChart = echarts.init(this.$refs.qualificationTrendChart);
      
      const qualificationTrend = this.chartData.repairEvaluation?.qualificationTrend || [];
      if (qualificationTrend.length === 0) return;
      
      const xData = qualificationTrend.map(item => item.timePoint || item.month);
      const rateData = qualificationTrend.map(item => item.qualificationRate);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{a}: {c}%'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xData
        },
        yAxis: {
          type: 'value',
          min: 'dataMin',
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: '维修合格率',
            type: 'line',
            smooth: true,
            data: rateData,
            itemStyle: {
              color: '#67C23A'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
                { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            markLine: {
              silent: true,
              lineStyle: {
                color: '#F56C6C'
              },
              data: [
                {
                  yAxis: 90,
                  name: '合格率下限',
                  label: {
                    formatter: '90%',
                    position: 'insideEndTop'
                  }
                }
              ].filter(item => item.yAxis !== null && item.yAxis !== undefined && !isNaN(item.yAxis))
            }
          }
        ]
      };
      
      this.qualificationTrendChart.setOption(option);
    }
  }
}
</script>

<style scoped>
.repair-statistics {
  padding: 10px 0;
}
.summary-card {
  height: 120px;
  margin-bottom: 20px;
}
.summary-header {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}
.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}
.summary-footer {
  font-size: 12px;
  color: #909399;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chart-row {
  margin-bottom: 20px;
}
.chart-card {
  height: 100%;
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chart-container {
  height: 300px;
  width: 100%;
}
</style> 